package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Sound;
import com.tanhua.domain.vo.SoundVo;
import com.tanhua.dubbo.api.SoundApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.job.SoundJob;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * @author WDY
 * @date Created in 2021/3/1 11:29
 * @modified By  WDY in 2021/3/1 11:29
 * @description
 */
@Service
public class SoundService {
    @Reference
    private SoundApi soundApi;
    @Autowired
    private FastFileStorageClient fastFileStorageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 桃花传音
     *
     * @param soundFile 音频文件
     * @return
     */
    public ResponseEntity sendSoundMessage(MultipartFile soundFile) throws IOException {
        //获取当前用户的userId
        Long userId = UserHolder.getUserId();
        //上传语音文件到fastDFS
        //获取文件名
        String soundFileFilename = soundFile.getOriginalFilename();
        String soundFileSuffix = soundFileFilename.substring(soundFileFilename.lastIndexOf(".") + 1);
        StorePath storePath = fastFileStorageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(), soundFileSuffix, null);
        String soundPath = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        //创建Sound对象
        Sound sound = new Sound();
        sound.setSoundUrl(soundPath);
        sound.setUserId(userId);
        sound.setState(0);
        //完成发送语音功能
        soundApi.saveSound(sound);
        return ResponseEntity.ok(null);
    }

    /**
     * 接收桃花传音
     *
     * @return
     */
    public ResponseEntity getSoundMessage() {
        //记录访问次数
        int count =0;
        String key = redisTemplate.opsForValue().get("COUNT_TANHUA_SOUND_"+ UserHolder.getUserId());
        if (key == null) {
            count=count;
        }else{
            count = Integer.parseInt(key);
        }
        //查询所有语音信息
        List<Sound> soundList = soundApi.findSounds();
        //创建所有语音消息id的集合
        List<String> idList = new ArrayList<>();
        //随机获得一个语音消息
        for (Sound sound : soundList) {
            String sid = sound.getId().toHexString();
            Long soundUserId = sound.getUserId();
            if (!UserHolder.getUserId().equals(soundUserId)&& sound.getState()== 0) {
                idList.add(sid);
            }
        }
        Random random = new Random();
        String sid = idList.get(random.nextInt(idList.size()));
        //根据sid查询语音信息
        Sound sound = soundApi.getSoundMessage(sid);
        SoundVo vo = new SoundVo();
        UserInfo userInfo = userInfoApi.findById(sound.getUserId());
        vo.setId(sound.getUserId().intValue());
        BeanUtils.copyProperties(userInfo,vo);
        vo.setSoundUrl(sound.getSoundUrl());
        vo.setRemainingTimes(9-count);
        sound.setState(1);
        //更新状态
        soundApi.updateState(sound);
        count++;
        redisTemplate.opsForValue().set("COUNT_TANHUA_SOUND_"+ UserHolder.getUserId(), String.valueOf(count));
        //删除语音信息
        //soundApi.deleteSound(sid);
        return ResponseEntity.ok(vo);
    }
}